package de.hhbk.feedbackmodul.daobeans;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.hhbk.feedbackmodul.daointerfaces.QuestionDaoIF;
import de.hhbk.feedbackmodul.entities.Question;

@Stateless
public class QuestionDaoBean implements QuestionDaoIF {

	@PersistenceContext(unitName = "FeedbackModulEJB")
	private EntityManager manager;
	
	private Logger logger = Logger.getLogger(this.getClass());
	


	@SuppressWarnings("unchecked")
	@Override
	public List<Question> getAllQuestions() throws Exception  {
		try
		{
			Query query = manager.createQuery("select q from Question q left join fetch q.antwortmoeglichkeiten", Question.class);
			Set<Question> result = new HashSet<Question>(query.getResultList());
			return new ArrayList<Question>(result);
		}
		catch(Exception e)
		{
			logger.error("Error while reading Questions: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void createQuestion(Question question) throws Exception {
		try
		{
			manager.persist(question);
		}
		catch(Exception e)
		{
			logger.error("Error while persisting Question: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void updateQuestion(Question question) throws Exception {
		try
		{
			manager.merge(question);
		}
		catch(Exception e)
		{
			logger.error("Error while updating Question: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void deleteQuestion(Question question) throws Exception {
		try
		{
			Question questionToDelete = manager.find(Question.class, question.getId());
			manager.remove(questionToDelete);
		}
		catch(Exception e)
		{
			logger.error("Error while deleting Question: "+e.getMessage(), e);
			throw e;
		}
	}

}
